import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Row,
  Col,
  Statistic,
  Typography,
  Drawer,
  Descriptions,
  Divider,
  DatePicker,
  message,
  Modal,
  Tooltip,
  Spin,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  FilterOutlined,
  ReloadOutlined,
  SyncOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import ResizableTable from '../components/ResizableTable';
import {
  fetchFunds,
  searchFunds,
  fetchFund,
  fetchFundPerformance,
  createSyncTask,
  fetchSyncStatus,
  setFilters,
  clearFilters,
} from '../store/slices/dataSlice';
import MainLayout from '../components/Layout/MainLayout';
import { FundData, RISK_LEVELS } from '../types';

const { Title, Text } = Typography;
const { Option } = Select;
const { Search } = Input;
const { RangePicker } = DatePicker;

const Funds: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const {
    funds,
    currentFund,
    fundPerformance,
    syncStatus,
    loading,
    filters,
    pagination,
  } = useAppSelector((state: any) => state.data);
  
  const [detailVisible, setDetailVisible] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [syncing, setSyncing] = useState(false);

  useEffect(() => {
    dispatch(fetchFunds({ page: 1, page_size: 20 }));
  }, [dispatch]);

  const handleSearch = (value: string) => {
    setSearchValue(value);
    if (value.trim()) {
      dispatch(searchFunds({ keyword: value.trim() }));
    } else {
      dispatch(fetchFunds({ page: 1, page_size: 20 }));
    }
  };

  const handleFilterChange = (key: string, value: any) => {
    dispatch(setFilters({ [key]: value }));
    dispatch(fetchFunds({ ...filters, [key]: value }));
  };

  const handleClearFilters = () => {
    dispatch(clearFilters());
    setSearchValue('');
    dispatch(fetchFunds({ page: 1, page_size: 20 }));
  };

  const handleViewDetail = async (fund: FundData) => {
    await dispatch(fetchFund(fund.fund_code));
    await dispatch(fetchFundPerformance({ fundCode: fund.fund_code }));
    setDetailVisible(true);
  };

  const handleSyncData = async () => {
    setSyncing(true);
    try {
      await dispatch(createSyncTask({ data_source_id: 1, sync_type: 'fund_data' })).unwrap();
      message.success('数据同步任务已创建');
      // 定期检查同步状态
      const checkStatus = setInterval(async () => {
        const status = await dispatch(fetchSyncStatus()).unwrap();
        if (status.status === 'completed' || status.status === 'failed') {
          clearInterval(checkStatus);
          setSyncing(false);
          if (status.status === 'completed') {
            message.success('数据同步完成');
            dispatch(fetchFunds({ page: 1, page_size: 20 }));
          } else {
            message.error('数据同步失败');
          }
        }
      }, 3000);
    } catch (error) {
      setSyncing(false);
      message.error('创建同步任务失败');
    }
  };

  const handleTableChange = (paginationInfo: any) => {
    dispatch(fetchFunds({
      ...filters,
      page: paginationInfo.current,
      page_size: paginationInfo.pageSize,
    }));
  };

  // 基金类型中文映射
  const fundTypeMap: { [key: string]: string } = {
    'stock': '股票型',
    'bond': '债券型', 
    'hybrid': '混合型',
    'money': '货币型',
    'index': '指数型',
    'qdii': 'QDII',
    'fof': 'FOF',
    'other': '其他',
    'balanced': '平衡型'
  };

  const columns = [
    {
      title: '基金名称',
      dataIndex: 'fund_name',
      key: 'fund_name',
      ellipsis: true,
      render: (text: string, record: FundData) => (
        <Button
          type="link"
          onClick={() => handleViewDetail(record)}
          style={{ padding: 0, textAlign: 'left' }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '基金代码',
      dataIndex: 'fund_code',
      key: 'fund_code',
      width: 120,
      render: (text: string, record: FundData) => (
        <Button
          type="link"
          onClick={() => navigate(`/funds/${text}`)}
          style={{ padding: 0, color: '#1890ff' }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '基金类型',
      dataIndex: 'fund_type',
      key: 'fund_type',
      width: 100,
      render: (text: string, record: FundData) => (
        <Tag color="blue">{fundTypeMap[text] || text}</Tag>
      ),
    },
    {
      title: '基金公司',
      dataIndex: 'fund_company',
      key: 'fund_company',
      width: 150,
      ellipsis: true,
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 100,
      render: (level: number) => (
        <Tag color={level <= 2 ? 'green' : level <= 3 ? 'orange' : 'red'}>
          {RISK_LEVELS[level as keyof typeof RISK_LEVELS]}
        </Tag>
      ),
    },
    {
      title: '年化收益率',
      dataIndex: 'annual_return',
      key: 'annual_return',
      width: 120,
      render: (value: number) => (
        <Text type={value >= 0 ? 'success' : 'danger'}>
          {value >= 0 ? '+' : ''}{value.toFixed(2)}%
        </Text>
      ),
      sorter: true,
    },
    {
      title: '基金规模',
      dataIndex: 'fund_size',
      key: 'fund_size',
      width: 120,
      render: (value: number) => `${(value / 100000000).toFixed(2)}亿`,
      sorter: true,
    },
    {
      title: '管理费率',
      dataIndex: 'management_fee',
      key: 'management_fee',
      width: 100,
      render: (value: number) => `${value.toFixed(2)}%`,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: FundData) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<LineChartOutlined />}
            onClick={() => navigate(`/funds/${record.fund_code}/chart`)}
          >
            图表
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>基金数据</Title>
          <Text type="secondary">查看和分析基金数据信息</Text>

        </div>

        {/* 统计概览 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="基金总数"
                value={pagination.total_count}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="平均年化收益"
                value={funds.length > 0 ? 
                  funds.reduce((sum: number, f: FundData) => sum + f.annual_return, 0) / funds.length : 0
                }
                precision={2}
                valueStyle={{ color: '#52c41a' }}
                suffix="%"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总规模"
                value={funds.length > 0 ? 
                  funds.reduce((sum: number, f: FundData) => sum + f.fund_size, 0) / 100000000 : 0
                }
                precision={2}
                valueStyle={{ color: '#722ed1' }}
                suffix="亿"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="同步状态"
                value={syncStatus?.status || '未知'}
                valueStyle={{ 
                  color: syncStatus?.status === 'completed' ? '#52c41a' : 
                         syncStatus?.status === 'running' ? '#1890ff' : '#ff4d4f'
                }}
              />
            </Card>
          </Col>
        </Row>

        {/* 搜索和筛选 */}
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={12} md={8}>
              <Search
                placeholder="搜索基金名称或代码"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                onSearch={handleSearch}
                enterButton={<SearchOutlined />}
                allowClear
              />
            </Col>
            <Col xs={24} sm={12} md={4}>
              <Select
                placeholder="基金类型"
                value={filters.fund_type}
                onChange={(value) => handleFilterChange('fund_type', value)}
                allowClear
                style={{ width: '100%' }}
              >
                <Option value="stock">股票型</Option>
                <Option value="bond">债券型</Option>
                <Option value="hybrid">混合型</Option>
                <Option value="money">货币型</Option>
                <Option value="index">指数型</Option>
                <Option value="qdii">QDII</Option>
                <Option value="fof">FOF</Option>
                <Option value="other">其他</Option>
              </Select>
            </Col>
            <Col xs={24} sm={12} md={4}>
              <Select
                placeholder="风险等级"
                value={filters.risk_level}
                onChange={(value) => handleFilterChange('risk_level', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.entries(RISK_LEVELS).map(([key, value]) => (
                  <Option key={key} value={parseInt(key)}>
                    {value}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Space wrap>
                <Button
                  icon={<FilterOutlined />}
                  onClick={handleClearFilters}
                >
                  清除筛选
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() => dispatch(fetchFunds({ page: 1, page_size: 20 }))}
                >
                  刷新
                </Button>
                <Button
                  type="primary"
                  icon={<SyncOutlined spin={syncing} />}
                  onClick={handleSyncData}
                  loading={syncing}
                >
                  同步数据
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 基金列表 */}
        <Card title="基金列表">
          <ResizableTable
            columns={columns}
            dataSource={funds}
            loading={loading}
            rowKey="id"
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条基金`,
            }}
            onChange={handleTableChange}
            scroll={{ x: 1200 }}
          />
        </Card>

        {/* 基金详情抽屉 */}
        <Drawer
          title="基金详情"
          placement="right"
          width={700}
          open={detailVisible}
          onClose={() => setDetailVisible(false)}
        >
          {currentFund && (
            <div>
              <Descriptions
                title={currentFund.fund_name}
                bordered
                column={1}
                size="small"
              >
                <Descriptions.Item label="基金代码">
                  {currentFund.fund_code}
                </Descriptions.Item>
                <Descriptions.Item label="基金类型">
                  <Tag color="blue">{currentFund.fund_type_display || currentFund.fund_type}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="基金公司">
                  {currentFund.fund_company}
                </Descriptions.Item>
                <Descriptions.Item label="基金经理">
                  {currentFund.fund_manager}
                </Descriptions.Item>
                <Descriptions.Item label="成立日期">
                  {currentFund.establishment_date}
                </Descriptions.Item>
                <Descriptions.Item label="风险等级">
                  <Tag color={currentFund.risk_level <= 2 ? 'green' : currentFund.risk_level <= 3 ? 'orange' : 'red'}>
                    {RISK_LEVELS[currentFund.risk_level as keyof typeof RISK_LEVELS]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="基金规模">
                  {(currentFund.fund_size / 100000000).toFixed(2)}亿
                </Descriptions.Item>
                <Descriptions.Item label="年化收益率">
                  <Text type={currentFund.annual_return >= 0 ? 'success' : 'danger'}>
                    {currentFund.annual_return >= 0 ? '+' : ''}{currentFund.annual_return.toFixed(2)}%
                  </Text>
                </Descriptions.Item>
                <Descriptions.Item label="管理费率">
                  {currentFund.management_fee.toFixed(2)}%
                </Descriptions.Item>
                <Descriptions.Item label="托管费率">
                  {currentFund.custodian_fee.toFixed(2)}%
                </Descriptions.Item>
              </Descriptions>
              
              {fundPerformance && (
                <>
                  <Divider />
                  <Title level={4}>业绩表现</Title>
                  <Row gutter={[16, 16]}>
                    <Col span={8}>
                      <Statistic
                        title="近1年收益"
                        value={fundPerformance.return_1y}
                        precision={2}
                        suffix="%"
                        valueStyle={{ 
                          color: fundPerformance.return_1y >= 0 ? '#52c41a' : '#ff4d4f'
                        }}
                      />
                    </Col>
                    <Col span={8}>
                      <Statistic
                        title="近3年收益"
                        value={fundPerformance.return_3y}
                        precision={2}
                        suffix="%"
                        valueStyle={{ 
                          color: fundPerformance.return_3y >= 0 ? '#52c41a' : '#ff4d4f'
                        }}
                      />
                    </Col>
                    <Col span={8}>
                      <Statistic
                        title="波动率"
                        value={fundPerformance.volatility}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Col>
                  </Row>
                  <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                    <Col span={8}>
                      <Statistic
                        title="夏普比率"
                        value={fundPerformance.sharpe_ratio}
                        precision={2}
                        valueStyle={{ color: '#722ed1' }}
                      />
                    </Col>
                    <Col span={8}>
                      <Statistic
                        title="最大回撤"
                        value={fundPerformance.max_drawdown}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#ff4d4f' }}
                      />
                    </Col>
                  </Row>
                </>
              )}
            </div>
          )}
        </Drawer>
      </div>
    </MainLayout>
  );
};

export default Funds;